package bigdata.config;

import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import java.io.IOException;
import java.util.Properties;

@Configuration
public class FreeMarkerConfig {
    @Bean
    public ViewResolver viewResolver() {
        FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
        resolver.setViewClass(org.springframework.web.servlet.view.freemarker.FreeMarkerView.class);
        //resolver.setCache(false);
        resolver.setSuffix(".html");
        resolver.setExposeSpringMacroHelpers(true);
        resolver.setExposeRequestAttributes(true);
        resolver.setExposeSessionAttributes(true);
        resolver.setRequestContextAttribute("request");
        resolver.setContentType("text/html; charset=UTF-8");
        return resolver;
    }

    @Bean
    public FreeMarkerConfigurer freemarkerConfigurer() throws IOException, TemplateException {
        // 默认内容
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        // 使用 shiro 标签
        //FreeMarkerConfigurerExtend configurer = new FreeMarkerConfigurerExtend();
        //
        FreeMarkerConfigurationFactory factory = new FreeMarkerConfigurationFactory();
        factory.setTemplateLoaderPaths("classpath:/templates/");
        factory.setDefaultEncoding("UTF-8");
        freemarker.template.Configuration configuration = factory.createConfiguration();
        configuration.setClassicCompatible(true);
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
        configurer.setConfiguration(configuration);
        //
        Properties settings = new Properties();
        //settings.put("template_update_delay", "0");
        settings.put("default_encoding", "UTF-8");
        settings.put("number_format", "0.##");
        settings.put("datetime_format", "yyyy-MM-dd HH:mm:ss");
        //用于解决前端报空指针问题
        settings.put("classic_compatible", true);
        configurer.setFreemarkerSettings(settings);
        return configurer;
    }
}
